﻿using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Linq;
using System.Text;
using System.Windows.Forms;

namespace Lapas.Common.Forms
{
    public class ListForm2 : BaseForm
    {
        #region UIControls
        private System.Windows.Forms.ToolStripButton newButton;
        private System.Windows.Forms.ToolStripButton exportButton;
        private System.Windows.Forms.ToolStripButton helpButton;
        private System.Windows.Forms.StatusStrip mainStatusStrip;
        private ToolStripButton deleteButton;
        private System.Windows.Forms.ToolStripButton modifyButton;
        protected ToolStripStatusLabel listFormStatusLabel;
        private ToolStripButton GrossButton;
        protected ToolStrip mainToolStrip;

        private void InitializeComponent()
        {
            System.ComponentModel.ComponentResourceManager resources = new System.ComponentModel.ComponentResourceManager(typeof(ListForm2));
            this.mainToolStrip = new System.Windows.Forms.ToolStrip();
            this.newButton = new System.Windows.Forms.ToolStripButton();
            this.modifyButton = new System.Windows.Forms.ToolStripButton();
            this.deleteButton = new System.Windows.Forms.ToolStripButton();
            this.GrossButton = new System.Windows.Forms.ToolStripButton();
            this.exportButton = new System.Windows.Forms.ToolStripButton();
            this.helpButton = new System.Windows.Forms.ToolStripButton();
            this.mainStatusStrip = new System.Windows.Forms.StatusStrip();
            this.listFormStatusLabel = new System.Windows.Forms.ToolStripStatusLabel();
            this.mainToolStrip.SuspendLayout();
            this.mainStatusStrip.SuspendLayout();
            this.SuspendLayout();
            // 
            // mainToolStrip
            // 
            this.mainToolStrip.Items.AddRange(new System.Windows.Forms.ToolStripItem[] {
            this.newButton,
            this.modifyButton,
            this.deleteButton,
            this.GrossButton,
            this.exportButton,
            this.helpButton});
            this.mainToolStrip.Location = new System.Drawing.Point(0, 0);
            this.mainToolStrip.Name = "mainToolStrip";
            this.mainToolStrip.Size = new System.Drawing.Size(685, 27);
            this.mainToolStrip.TabIndex = 0;
            this.mainToolStrip.Text = "toolStrip1";
            // 
            // newButton
            // 
            this.newButton.Image = ((System.Drawing.Image)(resources.GetObject("newButton.Image")));
            this.newButton.ImageTransparentColor = System.Drawing.Color.Magenta;
            this.newButton.Name = "newButton";
            this.newButton.Size = new System.Drawing.Size(66, 24);
            this.newButton.Text = "&Thêm";
            this.newButton.Click += new System.EventHandler(this.newButton_Click);
            // 
            // modifyButton
            // 
            this.modifyButton.Image = ((System.Drawing.Image)(resources.GetObject("modifyButton.Image")));
            this.modifyButton.ImageTransparentColor = System.Drawing.Color.Magenta;
            this.modifyButton.Name = "modifyButton";
            this.modifyButton.Size = new System.Drawing.Size(54, 24);
            this.modifyButton.Text = "&Sửa";
            this.modifyButton.Click += new System.EventHandler(this.modifyButton_Click);
            // 
            // deleteButton
            // 
            this.deleteButton.Image = global::Lapas.Common.Icons.delete1;
            this.deleteButton.ImageTransparentColor = System.Drawing.Color.Magenta;
            this.deleteButton.Name = "deleteButton";
            this.deleteButton.Size = new System.Drawing.Size(55, 24);
            this.deleteButton.Text = "&Xóa";
            this.deleteButton.Click += new System.EventHandler(this.deleteButton_Click);
            // 
            // GrossButton
            // 
            this.GrossButton.Image = ((System.Drawing.Image)(resources.GetObject("GrossButton.Image")));
            this.GrossButton.ImageTransparentColor = System.Drawing.Color.Magenta;
            this.GrossButton.Name = "GrossButton";
            this.GrossButton.Size = new System.Drawing.Size(82, 24);
            this.GrossButton.Text = "&Gộp mã";
            this.GrossButton.Click += new System.EventHandler(this.GrossButton_Click);
            // 
            // exportButton
            // 
            this.exportButton.Image = global::Lapas.Common.Icons.ExportIcon;
            this.exportButton.ImageTransparentColor = System.Drawing.Color.Magenta;
            this.exportButton.Name = "exportButton";
            this.exportButton.Size = new System.Drawing.Size(72, 24);
            this.exportButton.Text = "&Export";
            this.exportButton.Click += new System.EventHandler(this.exportButton_Click);
            // 
            // helpButton
            // 
            this.helpButton.ImageTransparentColor = System.Drawing.Color.Magenta;
            this.helpButton.Name = "helpButton";
            this.helpButton.Size = new System.Drawing.Size(69, 24);
            this.helpButton.Text = "Trợ giú&p";
            // 
            // mainStatusStrip
            // 
            this.mainStatusStrip.Items.AddRange(new System.Windows.Forms.ToolStripItem[] {
            this.listFormStatusLabel});
            this.mainStatusStrip.Location = new System.Drawing.Point(0, 440);
            this.mainStatusStrip.Name = "mainStatusStrip";
            this.mainStatusStrip.Size = new System.Drawing.Size(685, 22);
            this.mainStatusStrip.TabIndex = 1;
            this.mainStatusStrip.Text = "statusStrip1";
            // 
            // listFormStatusLabel
            // 
            this.listFormStatusLabel.Name = "listFormStatusLabel";
            this.listFormStatusLabel.Size = new System.Drawing.Size(0, 17);
            // 
            // ListForm2
            // 
            this.ClientSize = new System.Drawing.Size(685, 462);
            this.Controls.Add(this.mainToolStrip);
            this.Controls.Add(this.mainStatusStrip);
            this.Icon = ((System.Drawing.Icon)(resources.GetObject("$this.Icon")));
            this.KeyPreview = true;
            this.MinimizeBox = false;
            this.Name = "ListForm2";
            this.StartPosition = System.Windows.Forms.FormStartPosition.CenterScreen;
            this.mainToolStrip.ResumeLayout(false);
            this.mainToolStrip.PerformLayout();
            this.mainStatusStrip.ResumeLayout(false);
            this.mainStatusStrip.PerformLayout();
            this.ResumeLayout(false);
            this.PerformLayout();

        }
        #endregion UIControls

        #region Private Properties

        private DataGridView _grid = null;
        private bool _isStockGrid = false;
        //private bool hideDeleteButton;

        //DUNG CHO HEADER FILE EXCEL EXPORT
        private string _headerExcelFile;
        private string _styleExcelFile;
        private string _footerExcelFile;
        #endregion Private Properties

        #region Protected Properties

        protected virtual DataGridView Grid
        {
            get
            {
                return _grid;
            }


        }

        protected bool IsStockGrid
        {
            get { return _isStockGrid; }
            set { _isStockGrid = value; }
        }
        /// <summary>
        /// 
        /// </summary>
        protected ToolStripButton DeleteButton
        {
            get
            {
                return this.deleteButton;
            }

        }


        /// <summary>
        /// Hide Delete button and deactivate default delete function
        /// </summary>
        public bool HideDeleteButton
        {
            get { return !DeleteButton.Visible; }
            set { DeleteButton.Visible = !value; }
        }


        protected ToolStripButton NewButton
        {
            get
            {
                return this.newButton;
            }
        }

        protected ToolStripButton ModifyButton
        {
            get
            {
                return this.modifyButton;
            }
        }

        /// <summary>
        /// 20080125 Haids: update Export Button
        /// </summary>
        protected ToolStripButton ExportButton
        {
            get
            {
                return this.exportButton;
            }
        }

        protected ToolStrip ListFormToolStrip
        {
            get
            {
                return this.mainToolStrip;
            }
        }

        protected string HeaderExcelFile
        {
            set
            {
                _headerExcelFile = value;
            }
        }

        protected string StyleExcelFile
        {
            set
            {
                _styleExcelFile = value;
            }
        }

        protected string FooterExcelFile
        {
            set
            {
                _footerExcelFile = value;
            }
        }
        #endregion Protected Properties

        #region Public Properties

        public BindingSource bindingSource = new BindingSource();

        private bool _bindDataOnLoad;
        /// <summary>
        /// cho phép chạy hàm bind data trong lúc load
        /// giá trị mặc định là false
        /// 20071112 TriDM
        /// </summary>
        public bool BindDataOnLoad
        {
            get { return _bindDataOnLoad; }
            set { _bindDataOnLoad = value; }
        }

        #endregion Public Properites

        #region Virtual Methodes

        protected virtual void BindData()
        {
            if (Grid != null)
            {
                Grid.DataSource = bindingSource;
                listFormStatusLabel.Text = string.Format("Tổng cộng có {0} bản ghi.", Grid.RowCount.ToString("n0"));
            }
        }

        /// <summary>
        /// 20091023 Huannv
        /// Ham thuc hien load tong so ban ghi (trong truong hop khong bind data theo DataSource).
        /// </summary>
        /// <param name="total">Total of records</param>
        protected virtual void LoadTotalRecords(int total)
        {
            listFormStatusLabel.Text = string.Format("Tổng cộng có {0} bản ghi.", total.ToString("n0"));
        }

        protected virtual void OnNew(object sender, EventArgs e)
        {
            DisplayEditForm(EditForm.EditFormAction.Insert);
        }

        protected virtual void OnModify(object sender, EventArgs e)
        {
            if (Grid == null) return;
            if (Grid.RowCount > 0)
                DisplayEditForm(EditForm.EditFormAction.Change);
        }

        protected virtual void OnDelete(object sender, EventArgs e)
        {

        }

        protected virtual void OnGross(object sender, EventArgs e)
        {

        }

        protected virtual void OnExport(object sender, EventArgs e)
        {
            if (Grid == null) return;
            //if Grid.DatSource==null then???
            //still show error when DataSource is null. review???

            //VanVo modify on 20070725 to export seleted rows on grid
            if (Grid.SelectedRows.Count == 0)
            {
                DisplayMessage.ShowNotice("Hãy chọn dữ liệu cần Export!");
                return;
            }
            using (SaveFileDialog saveFileDialog = new SaveFileDialog())
            {
                try
                {
                    saveFileDialog.Filter = "Excel files (*.xls)|*.xls|All files (*.*)|*.*";
                    saveFileDialog.FileName = this.Text;
                    saveFileDialog.Title = "Xuất ra " + this.Text;

                    if (saveFileDialog.ShowDialog() == DialogResult.OK && saveFileDialog.FileName.Length > 0)
                    {
                        DataSet dataSet = new DataSet();
                        ObjectAdapter objectAdapter = new ObjectAdapter();
                        DataTable dataTable = new DataTable();

                        //Lay toan bo du lieu trong grid xuat ra Excel
                        foreach (DataGridViewColumn column in Grid.Columns)
                        {

                            dataTable.Columns.Add(column.HeaderText, typeof(string));

                        }
                        int rCount = 0;
                        foreach (DataGridViewRow row in Grid.SelectedRows)
                        {
                            DataRow dataRow = dataTable.NewRow();

                            foreach (DataGridViewColumn column in Grid.Columns)
                            {
                                // 20070927 TriDM: bo sung neu cot bi null thi tra ra string.Empty
                                if (row.Cells[column.Index].Value == null)
                                {
                                    dataRow[column.Index] = string.Empty;
                                }
                                else
                                {
                                    try
                                    {
                                        //Chuyen column co dinh dang Guid ve int, Guid ko co y nghia voi khach hang
                                        Guid aa = new Guid(Convert.ToString(row.Cells[column.Index].Value));
                                        dataRow[column.Index] = ++rCount;//row.Cells[column.Index].Value.ToString();
                                    }
                                    catch
                                    {
                                        dataRow[column.Index] = row.Cells[column.Index].Value.ToString();
                                    }

                                }
                            }
                            dataTable.Rows.Add(dataRow);
                        }

                        //objectAdapter.Fill(dataSet, da);
                        dataSet.Tables.Add(dataTable);
                        ExelUtilities.ExportToExcel(dataSet, saveFileDialog.FileName, _headerExcelFile, _styleExcelFile, _footerExcelFile);
                        DisplayMessage.ShowNotice("Export dữ liệu thành công");
                    }
                }
                catch (Exception ex)
                {
                    DisplayMessage.ShowError(ex.Message);
                }
            }
        }

        protected virtual void FormatGrid()
        {
            if (Grid != null)
                Lapas.Common.UIFormat.FormatGrid(Grid, true, true);
        }

        protected virtual void FormatBoldGrid()
        {

        }

        protected virtual void DisplayEditForm(EditForm.EditFormAction action)
        { }

        protected virtual void Grid_KeyDown(object sender, KeyEventArgs e)
        {
            switch (e.KeyCode)
            {
                case Keys.Delete:
                    if (!HideDeleteButton)
                        deleteButton_Click(null, null);
                    break;
                case Keys.F2:
                    {
                        DisplayEditForm(EditForm.EditFormAction.Change);
                        break;
                    }
                case Keys.Insert:
                    {
                        DisplayEditForm(EditForm.EditFormAction.Insert);
                        break;
                    }
                default:
                    break;
            }
        }

        protected virtual void Grid_CellDoubleClick(object sender, DataGridViewCellEventArgs e)
        {
            //Loai bo click vao header
            // (Old code) if (e.RowIndex > 0)
            // [Haids] [Edited] [20070622]
            // if e.RowIndex > 0 then sẽ không edit được bản ghi thứ nhất.
            if (e.RowIndex >= 0)
            {
                DisplayEditForm(EditForm.EditFormAction.Change);
            }
        }

        #endregion Virtual Methodes

        #region Button Events

        private void newButton_Click(object sender, EventArgs e)
        {
            OnNew(sender, e);
        }

        private void modifyButton_Click(object sender, EventArgs e)
        {
            OnModify(sender, e);
        }

        private void deleteButton_Click(object sender, EventArgs e)
        {
            if (Grid == null) return;
            if (Grid.SelectedRows.Count > 0)
            {
                if (DisplayMessage.ShowConfirm("Bạn có chắc chắn muốn xóa?"))
                {
                    OnDelete(sender, e);
                }
            }
        }

        // 20070820 TriDM: neu Grid=null return
        private void exportButton_Click(object sender, EventArgs e)
        {
            OnExport(sender, e);
        }

        #endregion Button Events

        public ListForm2()
        {
            InitializeComponent();
            helpButton.Visible = false;
        }

        protected override void OnLoad(EventArgs e)
        {
            base.OnLoad(e);
            //DeleteButton.Visible = !HideDeleteButton;
            this.Icon = base.Icon;
            if (Grid != null)
            {

                this.Grid.CellDoubleClick += new DataGridViewCellEventHandler(Grid_CellDoubleClick);
                this.Grid.KeyDown += new KeyEventHandler(Grid_KeyDown);
            }
            FormatGrid();
            // Bind data to Grid
            BindData();
            FormatBoldGrid();
        }

        private void GrossButton_Click(object sender, EventArgs e)
        {
            if (Grid == null) return;
            if (Grid.SelectedRows.Count > 0)
            {
                OnGross(sender, e);
            }
        }
    }
}
